<?php

abstract class YouNet_Controller_Action extends Zend_Controller_Action {
	
	/**
	 *
	 * @var YouNet_Social_Plugin
	 */
	protected $_social;
	protected $_params;
	protected $_user;
	protected $_id_user;
	
    public function init()
    {
    	parent::init();    	
    	
        $this->_social = YouNet_Api::getInstance()->getSocialPlugin();
        $this->view->social = $this->_social;
        
        $this->_params = $this->_getAllParams();
        Zend_Registry::set('params', $this->_params);
        
        $this->_helper->layout->setLayout('layout_' . strtolower($this->_social->getName()));
        
        if ($this->getRequest()->getActionName() == 'logout')
        	return;
        	
        $this->_authenticate();
        $this->_authorize();
        
        $this->_id_user = $this->_social->getIdUser();
        $this->_id_social = $this->_social->getIdSocial();
		$this->_user = $this->_social->getUser();
        $this->_params['id_user'] = $this->_id_user;
        $this->_params['id_social'] = $this->_id_social;
    }		
    
    private function _authenticate()
    {
    	
    } 
    
    private function _authorize()
    {
    	$acl = Zend_Registry::get('acl');
    	
    	$module = $this->_request->getModuleName();
    	$controller = $this->_request->getControllerName();
    	$action = $this->_request->getActionName();
    	
    	$user_roles = $this->_social->getUser()->getRoles();
    	$is_authorized = false;    	
    	foreach ($user_roles as $role)
    	{
    		if ($acl->isAllowed($role, $module . ':' . $controller, $action))
    		{
    			$is_authorized = true;
    			break;
    		}
    	} 
    	
    	if (!$is_authorized)
    	{
    		$this->_social->handleFailedAuthorization($this->_getRedirectUrlForAuthorization());
    	}
    }
    
    protected function translate($word)
    {
    	return $this->view->translate($word);
    } 
    
    protected function _getRedirectUrlForAuthorization()
    {
    	return '/';
    }
	
	public function indexAction() 
    {
    	return $this->_forward('list');
    }
    
	/**
	 * Use to disable auto-render
	 * @return void
	 */
	public function disableAutoRender()
	{
		$this->_helper->layout->disableLayout();
		$this->_helper->viewRenderer->setNoRender(TRUE);
	}
}